import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:home_framework/models/dynamic_entity.dart';
import 'package:home_framework/view_models/dynamic/dynamic_model.dart';
import 'package:provider/provider.dart';

class DynamicDetailPage extends StatefulWidget {
  final String id;
  DynamicDetailPage(this.id, {Key key}) : super(key: key);

  _DynamicDetailState createState() => _DynamicDetailState();
}

class _DynamicDetailState extends State<DynamicDetailPage> {
  @override
  void initState() {
    super.initState();
    context.read<DynamicModel>().getDynamic(widget.id).then((success) {
      if (success) {
        context.read<DynamicModel>().updateViewCount(widget.id);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    DynamicEntity currentDynamic = context.watch<DynamicModel>().currentDynamic;
    return Scaffold(
      appBar: AppBar(
        title: Text('动态详情'),
        brightness: Brightness.dark,
      ),
      body: currentDynamic == null
          ? Center(
              child: Text('请稍候...'),
            )
          : _getDetailWidget(currentDynamic),
    );
  }

  Widget _getDetailWidget(DynamicEntity currentDynamic) {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: Container(
            margin: EdgeInsets.fromLTRB(10, 10, 10, 5),
            child: Text(
              currentDynamic.title,
              style: TextStyle(
                fontSize: 16.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
        _viewCountWrapper(
            context.watch<DynamicModel>().currentDynamic.viewCount.toString()),
        SliverToBoxAdapter(
          child: CachedNetworkImage(
            imageUrl: currentDynamic.imageUrl,
            height: 200,
            fit: BoxFit.fill,
          ),
        ),
        SliverToBoxAdapter(
          child: Container(
            margin: EdgeInsets.all(10),
            child: Text(
              currentDynamic.content,
              style: TextStyle(
                fontSize: 14.0,
              ),
            ),
          ),
        ),
      ],
    );
  }

  SliverToBoxAdapter _viewCountWrapper(String text) {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.fromLTRB(10, 0, 10, 10),
        height: 20,
        child: Row(children: [
          Icon(
            Icons.remove_red_eye_outlined,
            size: 14.0,
            color: Colors.grey,
          ),
          SizedBox(width: 5),
          Text(
            text,
            style: TextStyle(color: Colors.grey, fontSize: 14.0),
          ),
        ]),
      ),
    );
  }
}
